import { Injectable } from '@nestjs/common';
import { CreateAttachementDto } from './dto/create-attachement.dto';
import { UpdateAttachementDto } from './dto/update-attachement.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Attachement } from './entities/attachement.entity';
import { Between, FindOptionsWhere, Like, Repository } from 'typeorm';
import * as fs from 'fs';
import * as path from 'path';
import { BusinessException } from '@/common';
import { IPaginationOptions, paginate } from 'nestjs-typeorm-paginate';
import { attachementQueryVo } from '@/common/interface';
const FILE_PATH = '/uploads/';
@Injectable()
export class AttachementService {
  constructor(
    @InjectRepository(Attachement)
    private readonly attachementRepository: Repository<Attachement>
  ) {}

  upload(file: any) {
    // path 变为指定 格式
    file.url = FILE_PATH + file.filename;
    const { originalname, fieldname, encoding, destination, path, ..._file } =
      file;
    return {
      name: originalname,
      ..._file
    };
  }

  findAll(option: IPaginationOptions, attachementQuery: attachementQueryVo) {
    const {filename, name, queryDate, minSize, maxSize} = attachementQuery
    const where: FindOptionsWhere<Attachement> = {}
    if(filename){
      where.filename = Like(`%${filename}%`)
    }
    if(name){
      where.name = Like(`%${name}%`)
    }
    if(queryDate?.length>0){
      where.createdAt = Between(queryDate[0], queryDate[1])
    }
    if(minSize && maxSize){
      where.size = Between(minSize, maxSize)
    }

    return paginate(this.attachementRepository, option, {
      where
    });
  }

  findOne(id: number) {
    return this.attachementRepository.findOneBy({ id });
  }

  async update(updateAttachementDto: UpdateAttachementDto) {
    const attachement = new Attachement();
    ['id', 'name', 'filename', 'minetype', 'size', 'url'].forEach((v) => {
      attachement[v] = updateAttachementDto[v];
    });

    return this.attachementRepository.save(attachement)
  }

  async remove(id: number) {
    const attachement = await this.findOne(id);
    if (!attachement) {
      throw new BusinessException({ code: 0, message: '数据不存在' });
    }
    // 删除硬盘附件
    if (attachement.url) {
      const filePath = path.join(process.cwd(), attachement.url);

      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    }
    // 删除实体数据
    return this.attachementRepository.remove(attachement);
  }

  async removeFile(id: number) {
    const attachement = await this.findOne(id);
    // 删除硬盘附件
    if (attachement.url) {
      const filePath = path.join(process.cwd(), attachement.url);

      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    }
  }
}
